from collections.abc import Generator
from typing import Any
import os

from dify_plugin import Tool
from dify_plugin.entities.tool import ToolInvokeMessage

class XmindParserTool(Tool):
    def _invoke(self, tool_parameters: dict[str, Any]) -> Generator[ToolInvokeMessage]:
        file = tool_parameters.get("xmind_file", None)
        content_type = tool_parameters.get("output_type", 'json')

        if not file:
            raise ValueError("Xmind file is required")
        file_name = file.filename
        file_extension = os.path.splitext(file_name)[-1].lower()
        file_bytes = file.blob
        if file_extension != '.xmind':
            raise ValueError("Xmind文件后缀格式错误，当前仅支持.xmind文件后缀")
        if content_type not in {'json', 'xml'}:
            raise ValueError(f"不支持输出为 {content_type} 数据类型，当前仅支持输出json、xml数据格式")
        
        # 解析处理
        from tools.xmindparser import xmind_to_content
        content = xmind_to_content(file_bytes=file_bytes, file_type=content_type)

        yield self.create_variable_message("content", content)
        yield self.create_variable_message("content_type", content_type)
